import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../service/project.service';
import { Message } from 'primeng/api';
import { ActivatedRoute, Router } from '@angular/router';
import {CRUD_MODE} from '../../shared/config/app-settings';
import { MessageUtilsService } from '../../shared/services/message-utils.service';
import * as _ from 'lodash';
@Component({
  selector: 'app-project-grid',
  templateUrl: './project-grid.component.html',
  styleUrls: ['./project-grid.component.css']
})
export class ProjectGridComponent implements OnInit {
  CRUD_MODE = CRUD_MODE;
  msgs: Message[] = [];
  //p-table
  dataSource:any[];
  selectedColumns: any[];
  cols: any[];
  constructor(private route:ActivatedRoute,
    private router:Router,
    private projectService:ProjectService,
    private messageUtilsService:MessageUtilsService) { }

  ngOnInit() {
    //init table
    this.cols = [
      { field: 'id', header: 'ID' },
      { field: 'status', header: 'STATUS' },
      { field: 'name', header: 'Building Name' },
      { field: 'buildingAddress', header: 'Building Address' },
      { field: 'state', header: 'STATE' },
      { field: 'city', header: 'CITY' },
      { field: 'settlementDate', header: 'Settlement Date' },
      { field: 'updateTime', header: 'Last Update Time' }
    ];
    this.selectedColumns = _.cloneDeep(this.cols); //toggle cols
    this.selectedColumns.splice(0,1); //default hide first column
    this.loadAllPropertyList();
  }

  //ui-event
  onReload(){
    this.loadAllPropertyList();
  }

  onAddEntity(){
    this.router.navigate(['../project-detail/0'], {relativeTo: this.route, queryParams: { mode: CRUD_MODE.CREATE }  });
  }

  onEditRow(rowData){
    this.router.navigate(['../project-detail/'+rowData.id], {relativeTo: this.route, queryParams: { mode: CRUD_MODE.EDIT }  });
  }

  onViewRow(rowData){
    this.router.navigate(['../project-detail/'+rowData.id], { relativeTo: this.route, queryParams: { mode: CRUD_MODE.VIEW } });
  }

  onDeleteRow(rowData){
    this.projectService.patch(rowData.id, {status:'inactive'}).subscribe(
      (res)=>{
        this.messageUtilsService.showInfo(this.msgs, 'inactive success');
        this.loadAllPropertyList();
      }
    );
  }

 

  showInfo(message: string) {
    this.msgs.push({ severity: 'info', summary: 'Message', detail: message });
  }

  showError(message: string) {
    this.msgs.push({ severity: 'error', summary: 'Message', detail: message });
  }

  //server exchange



  loadAllPropertyList(){
    this.projectService.getAllPropertyLists().subscribe(
      (res)=>{
        // this.dataSource =  _.filter(res, (project)=>project['status'] !== 'inactive');
        this.dataSource = res;
      },
      (err)=>{
        this.showError(err);

      }
    )
  }

}
